package cn.zswltech.gruul.web.api.util;


import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * bifrost 请求信息
 *
 * @author xuluquan
 * @date 2020-04-03 10:46
 */
public class RequestUtils {

    /**
     * 前端referer信息
     */
    public static final String REFERER = "referer";

    /**
     * csrf token
     */
    public static final String X_CF_RANDOM = "X-Cf-Random";

    /**
     * 同源检测（Origin 和 Referer 验证）；
     */
    public static final String ORIGIN_SERVER = "originServer";


    /**
     * 获取bifrost请求参数
     *
     * @param request
     * @return 请求参数
     * @author xuluquan
     * @date 2020-04-03 11:00
     */
    public static Map<String, String> getRequestParams(HttpServletRequest request) {

        String encryptCSRFToken = request.getHeader(X_CF_RANDOM);
        String referer = request.getHeader(REFERER);
        String wlToken = CookieUtils.getWlToken(request);
        Map<String, String> params = new HashMap<>();
        params.put(X_CF_RANDOM, encryptCSRFToken);
        params.put(REFERER, referer);
        params.put(ORIGIN_SERVER, getIpAddr(request));
        params.put(CookieUtils.WL_TOKEN, wlToken);
        return params;
    }

    public static String getIpAddr(HttpServletRequest request) {
        Set<String> list = new HashSet<>();
        list.add(request.getRemoteAddr());
        list.add(request.getRemoteHost());
        list.add(request.getServerName());
        list.removeIf(Objects::isNull);
        return String.join(";", list);
    }
}
